<template>
  <div class="app-container">
    <el-form :model="conditionForm" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px" size="small">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="conditionForm.roleName" placeholder="请输入角色名称" clearable style="width: 240px"
          @keyup.enter="setCondition" />
      </el-form-item>
      <el-form-item label="状态" prop="flags">
        <el-select v-model="conditionForm.flags" placeholder="角色状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="conditionForm.dateTimes" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" style="width: 300px;"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="setCondition">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button size="medium" type="primary" plain icon="el-icon-plus" @click="handleAdd"
          v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="medium" type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:role:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="medium" type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:role:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="medium" type="warning" plain icon="el-icon-download" @click="handleExport"
          v-hasPermi="['system:role:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch="showSearch" @queryTable="selectData"
        @updateShowSearch="updateShowSearch"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="tableLoading" :data="dataTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色编号" prop="roleCode" width="150" />
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" width="100" key="flags">
        <template #default="scope">
          <el-switch v-model="scope.row.flags" :active-value="0" :inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template #default="scope">
          <span>{{ timeFormat(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <div v-if="!scope.row.isAdmin">
            <el-tooltip content="修改" placement="top" v-if="scope.row.roleCode !== 1">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:role:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.roleCode !== 1">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:role:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleCode !== 1">
              <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleDataScope(scope.row)"
                v-hasPermi="['system:role:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleCode !== 1">
              <el-button size="mini" type="text" icon="el-icon-user" @click="handleAuthUser(scope.row)"
                v-hasPermi="['system:role:edit']"></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :total="pageInfo.total" background layout="total,sizes, prev, pager, next"
      :page-size="pageInfo.pageSize" :current-page="pageInfo.pageIndex" :page-sizes="[10, 20, 30, 40, 50]"
      @size-change="pageSizeChange" @current-change="selectData" style="float:right;"></el-pagination>

    <AddRole :roleRef="roleRef" :form="form" :sys_normal_disable="sys_normal_disable" :title="title" :open="open"
      @cancel="cancel" @submitForm="submitForm" ref="addRoleRef" />
    <!-- 分配角色数据权限对话框 -->
    <AddRoleData :title="title" :openDataScope="openDataScope" @cancelData="cancelData" ref="addRoleDataRef">
    </AddRoleData>
  </div>
</template>

<script setup name="Role" lang="ts">
import { delRole, getRole, listRole, updateRole } from "@/requests/api/role";
// import { roleMenuTreeselect } from "@/requests/api/menu";
import { ref, reactive, toRefs, Ref, nextTick } from "vue";
import { useRouter } from "vue-router/composables";
import { dictTypeInit } from "../dict/data";
import { timeFormat, timeRangeTransform } from "@/utils/time";
import { useShowSearch } from "@/hooks/useShowSearch";
import { usePagination } from "@/hooks/usePagination";
import RightToolbar from '@/components/RightToolbar.vue';
import { queryParamsInit } from "@/views/data";
import { conditionCommonRole, purTableHeader, purTableProps, roleSearchformInit } from "./data";
import { useReset } from "@/hooks/useReset";
import { Message, MessageBox } from "element-ui";
import { exportExcel, filterExcelContentArr } from "@/utils/excel";
import AddRole from "./AddRole.vue";
import AddRoleData from "./AddRoleData.vue"

const router = useRouter();
// const { proxy }: any = getCurrentInstance();
const sys_normal_disable = ref(dictTypeInit)
const open = ref(false);
const { showSearch, updateShowSearch } = useShowSearch();
let selectedArr: Array<any> = []
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");


const openDataScope = ref(false);

const data = reactive({
  form: {
    roleName: "",
    roleCode: "",
    flags: 0,
    remark: "",
    businessId: ""
  },
  conditionForm: Object.assign({
    dateTimes: [],
  }, conditionCommonRole),
  queryParams: Object.assign({
    condition: Object.assign({
      "startTime": "",
      "endTime": ""
    }, conditionCommonRole)
  }, queryParamsInit),
});

const { conditionForm, queryParams, form } = toRefs(data);

/** 查询角色列表 */
const { dataTable,
  pageInfo,
  pageSizeChange,
  selectData, tableLoading } = usePagination(queryParams, listRole)
/** 搜索按钮操作 */
const setCondition = () => {
  console.log('查询条件user', conditionForm.value)
  pageInfo.value.pageIndex = 1;
  if (queryParams.value.condition) {
    const { dateTimes, roleCode, roleName, flags } = conditionForm.value
    queryParams.value.condition.flags = flags;
    queryParams.value.condition.roleName = roleName;
    queryParams.value.condition.roleCode = roleCode;
    timeRangeTransform(dateTimes, queryParams);
  }
  selectData();
}
const roleRef: Ref<any> = ref(null);
const queryRef: Ref<any> = ref(null);
const { reset, resetQuery } = useReset({
  form,
  formInit: Object.assign({}, roleSearchformInit),
  formRef: roleRef,
  conditionForm,
  conditionFormRef: queryRef,
  request: setCondition
})
/** 删除按钮操作 */
function handleDelete(row: any) {
  const roleCodes = row.businessId || ids.value;
  MessageBox.confirm('是否确认删除角色编号为"' + roleCodes + '"的数据项?').then(() => {
    return delRole(roleCodes);
  }).then(() => {
    selectData();
    Message.success("删除成功");
  }).catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
  const sheetArr = filterExcelContentArr(selectedArr, purTableProps, purTableHeader)
  console.log('过滤的值', sheetArr)
  exportExcel(`role_${new Date().getTime()}.xlsx`, sheetArr)
};
/** 多选框选中数据 */
function handleSelectionChange(selection: any) {
  selectedArr = selection;
  ids.value = selection.map((item: any) => item.businessId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 角色状态修改 */
function handleStatusChange(row: any) {
  console.log('row1', row, row.flags, row.flags == 0) // 应该是switch默认点击时有个前置的事件
  let text = row.flags === 0 ? "启用" : "停用";
  console.log('row2', row.flags)
  MessageBox.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?').then(() => {
    return updateRole(row);
  }).then(() => {
    Message.success(text + "成功");
  }).catch(function () {
    row.flags
      = row.flags
        === 0 ? 1 : 0; // 失败了返回去之前的状态
  });
}

/** 分配用户 */
function handleAuthUser(row: any) {
  router.push("/sysAdmin/roleSetting/authUser/" + row.businessId);
}

const addRoleRef: Ref<InstanceType<typeof AddRole> | null> = ref(null)
/** 添加角色 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加角色";
  addRoleRef.value?.getMenuTreeselect();
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
const cancelData = () => {
  openDataScope.value = false;
  // reset();
}
function submitForm() {
  open.value = false;
  selectData();
}


/** 修改角色 */
function handleUpdate(row: any) {
  reset();
  const businessId = row.businessId || ids.value;
  // const roleMenu = getRoleMenuTreeselect(roleCode);
  getRole(businessId).then(response => {
    console.log('res', response)
    form.value = response.data;
    // form.value.roleSort = Number(form.value.roleSort);
    open.value = true;
    nextTick(() => {
      // roleMenu.then((res) => {
      //   let checkedKeys = res.checkedKeys;
      //   checkedKeys.forEach((v) => {
      //     nextTick(() => {
      //       menuRef.value.setChecked(v, true, false);
      //     });
      //   });
      // });
    });
    title.value = "修改角色";
  });
}



const addRoleDataRef: Ref<any> = ref(null)
/** 分配数据权限操作 */
function handleDataScope(row: any) {
  reset();
  openDataScope.value = true;
  title.value = "分配数据权限";
  addRoleDataRef.value.initDataScope(row.businessId) //  roleCode
}
/** 提交按钮（数据权限） */
// function submitDataScope() {
//   if (form.value.roleCode != undefined) {
//     // form.value.deptIds = getDeptAllCheckedKeys();
//     dataScope(form.value).then(() => {
//       proxy.$modal.msgSuccess("修改成功");
//       openDataScope.value = false;
//       selectData();
//     });
//   }
// }
/** 取消按钮（数据权限）*/
// function cancelDataScope() {
//   openDataScope.value = false;
//   reset();
// }
selectData();
</script>
